<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryParamsRef" :inline="true" :model="queryParams" label-width="60px">
        <el-form-item label="收费时间">
          <el-date-picker v-model="dateRange" :disabled="queryParams.outpFeesMasterId != ''" :unlink-panels="true"
                          end-placeholder="结束日期" range-separator="截止"
                          start-placeholder="开始日期" type="datetimerange"
                          value-format="YYYY-MM-DD HH:mm:ss"></el-date-picker>
        </el-form-item>
        <el-form-item label="患者姓名" prop="name">
          <el-input v-model="queryParams.name" :disabled="queryParams.outpFeesMasterId != ''" clearable
                    placeholder="请输入患者姓名" @keyup.enter="handleQuery"/>
        </el-form-item>
        <el-form-item label="门诊号" prop="clinicNo">
          <el-input v-model="queryParams.clinicNo" :disabled="queryParams.outpFeesMasterId != ''" clearable
                    placeholder="请输入门诊号" @keyup.enter="handleQuery"/>
        </el-form-item>
        <el-form-item label="收据号" prop="serialNo">
          <el-input v-model="queryParams.serialNo" :disabled="queryParams.outpFeesMasterId != ''" clearable
                    placeholder="请输入收据号" @keyup.enter="handleQuery"/>
        </el-form-item>
        <el-form-item label="收款员" prop="operationUserName">
          <el-input v-model="queryParams.operationUserName" :disabled="queryParams.outpFeesMasterId != ''"
                    clearable
                    placeholder="请输入收款员" @keyup.enter="handleQuery"/>
        </el-form-item>
        <el-form-item label="费用状态" prop="chargeFlag">
          <el-select v-model="queryParams.chargeFlag" :disabled="queryParams.outpFeesMasterId != ''" class="width-120"
                     clearable placeholder="请选择费用状态">
            <el-option v-for="dict in dictDataMap['charge_flag_dict']" :key="dict.dictValue"
                       :label="dict.dictLabel"
                       :value="dict.dictValue"/>
          </el-select>
        </el-form-item>
        <el-row>
          <el-form-item>
            <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery"/>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
    <div>
      <el-row>
        <el-col class="mr20" style="max-width: 65%">
          <div>收费主记录</div>
          <el-table v-adaptive="310" :border="true" :data="outpFeesMasterList"
                    :header-cell-style="$headerCellStyle"
                    :stripe="true"
                    highlight-current-row @row-click="rowClick">
            <el-table-column :align="'center'" label="患者姓名" prop="name" width="80"/>
            <el-table-column :align="'center'" label="门诊号" prop="clinicNo" width="100"/>
            <el-table-column :align="'center'" label="收费时间" prop="createTime" width="130">
              <template #default="scope">
                                <span>{{
                                    $parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}")
                                  }}</span>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="收据号" prop="feesNo" width="110">
              <template #default="scope">
                <span style="color: rgb(51, 91, 249)">{{ scope.row.feesNo }}</span>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="总费用" prop="costs" width="120">
              <template #default="scope">
                            <span class="ys-css">{{
                                // parseFloat(scope.row.costs - scope.row.refundCharges + "").toFixed(2)
                                parseFloat(scope.row.costs).toFixed(2)
                              }}</span>元
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="应收费用" prop="charges" width="120">
              <template #default="scope">
                                <span class="ys-css">{{
                                    parseFloat(scope.row.charges).toFixed(2)
                                  }}</span>元
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="支付方式" prop="moneyType" width="70">
              <template #default="scope">
                <el-popover :title="scope.row.name + ' | 收据号' + scope.row.feesNo" :width="270"
                            placement="right"
                            trigger="hover">
                  <template #reference>
                    <el-button type="primary">详情</el-button>
                  </template>
                  <el-descriptions :border="true" :column="1" class="mt5 mr5 mb5 ml5">
                    <el-descriptions-item v-for="(item, index) in scope.row.paymentsMoneyVoList"
                                          :key="index"
                                          min-width="80px">
                      <template #label>
                        <div style="display: flex">
                          <div style="flex: 1">
                                                        <span style="font-weight: bold">{{ item.moneyTypeName }}
                                                        </span>
                          </div>
                        </div>
                      </template>
                      <span class="ys-css">{{ parseFloat(item.charges).toFixed(2) }}</span>元
                    </el-descriptions-item>
                  </el-descriptions>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="缴费标志" prop="chargeFlag" width="130">
              <template #default="scope">
                <dict-data-tag :options="dictDataMap['charge_flag_dict']"
                               :value="scope.row.chargeFlag"/>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="收款人"
                             prop="operationUserName" width="120"/>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="退费号"
                             prop="refundedFeesNo"
                             width="110"/>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="退费人"
                             prop="refundedPersonName" width="80"/>
            <!--                        <el-table-column :align="'left'" label="退费金额" prop="refundCharges" width="110">-->
            <!--                            <template #default="scope">-->
            <!--                                <span class="ret-ys-css">{{-->
            <!--                                        parseFloat(scope.row.refundCharges + "").toFixed(2)-->
            <!--                                    }}</span>元-->
            <!--                            </template>-->
            <!--                        </el-table-column>-->
            <el-table-column :align="'center'" label="结账号" prop="acctNo" width="65"/>
            <el-table-column :align="'center'" class-name="small-padding fixed-width" fixed="right" label="操作"
                             width="150">
              <template #default="scope">
                <el-tooltip v-if="scope.row.chargeFlag==='2'" class="item" content="打印收费票据" effect="dark"
                            placement="top">
                  <el-button circle type="success" @click="printInvoiceIssueFun(scope.row)">
                    <template #icon>
                      <i-ep-printer/>
                    </template>
                  </el-button>
                </el-tooltip>
                <el-tooltip class="item" content="小票打印" effect="dark" placement="top">
                  <el-button circle v-if="scope.row.chargeFlag==='2'" type="primary" @click="prescPrint(scope.row)">
                    <template #icon>
                      <i-ep-printer/>
                    </template>
                  </el-button>
                </el-tooltip>
                <el-tooltip class="item" content="电子发票开具" effect="dark" placement="left">
                  <el-button v-if="scope.row.chargeFlag==='2'" circle type="primary" @click="printMasterFun(scope.row)">
                    <template #icon>
                      <svg-icon :icon-class="'kaipiao'"/>
                    </template>
                  </el-button>
                </el-tooltip>
                <el-tooltip class="item" content="冲红" effect="dark" placement="top">
                  <el-button v-if="scope.row.chargeFlag==='4'" circle type="warning"
                             @click="writeOffEBillFun(scope.row)">
                    <template #icon>
                      <svg-icon :icon-class="'cheXiao'"/>
                    </template>
                  </el-button>
                </el-tooltip>
                <el-tooltip class="item" content="作废" effect="dark" placement="right">
                  <el-button circle type="danger" @click="abolishFun(scope.row)">
                    <template #icon>
                      <svg-icon icon-class="abolish"/>
                    </template>
                  </el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="total > 0" v-model:limit="queryParams.pageSize"
                      v-model:page="queryParams.pageNum"
                      :total="total" @pagination="getList"/>
        </el-col>
        <el-col :span="8">
          <div>收费明细</div>
          <el-table v-adaptive="310" :border="true" :data="outpFeesDetailList"
                    :header-cell-style="$headerCellStyle"
                    :span-method="objectSpanMethod"
                    :stripe="true" highlight-current-row>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="申请单号" prop="applyNo"
                             width="100"/>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="诊疗项目名称"
                             min-width="120"
                             prop="packItemName"/>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="项目名称"
                             prop="itemName"
                             width="100"/>
            <el-table-column :align="'center'" label="缴费标志" prop="chargeFlag" width="130">
              <template #default="scope">
                <dict-data-tag :options="dictDataMap['charge_flag_dict']"
                               :value="scope.row.chargeFlag"/>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="项目类型" prop="itemClass" width="70">
              <template #default="scope">
                <dict-data-tag :options="dictDataMap['bill_item_class_dict']"
                               :value="scope.row.itemClass"/>
              </template>
            </el-table-column>
            <!-- <el-table-column
              label="项目编码"
              :align="'center'"
              prop="itemCode"
              width="90"
              :show-overflow-tooltip="true"
            /> -->
            <el-table-column :align="'center'" label="单价" prop="price" width="90">
              <template #default="scope">
                <span class="ys-css">{{ parseFloat(scope.row.price).toFixed(2) }}</span>元
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="数量" prop="num" width="51"/>
            <el-table-column :align="'center'" fixed="right" label="实收费用" prop="charges" width="110">
              <template #default="scope">
                <span class="ys-css">{{ parseFloat(scope.row.charges).toFixed(2) }}</span>元
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script lang="ts">
export default {
  name: "OutpFeesQueryIndex",
};
</script>
<script setup lang="ts">
import {abolishOutpFeesMaster, selectPageOutpFeesMaster, getInvoiceIssuePdfUrl} from "@/api/finance/outpFeesMaster.ts";
import {listOutpFeesDetail} from "@/api/finance/outpFeesDetail.ts";
import {useUserStoreHook} from "@/store/modules/user";
import {useDictStoreHook} from "@/store/modules/dict";
import {ElMessage} from "element-plus";
import {invoiceEBillOutpatient, writeOffEBill} from "@/api/openApi/electronicInvoice/invoiceInvalidPaper.ts";

const dictStore = useDictStoreHook();
const {proxy} = getCurrentInstance() as any;
const queryParamsRef = ref();
const total = ref(0);
const outpFeesMasterList = ref<any>([]);
const outpFeesDetailList = ref<any>([]);
const useUserStore = useUserStoreHook();
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;
const date = proxy.$parseTime(new Date(), "{y}-{m}-{d} ");
const dictDataMap = ref(
  dictStore.isTypeGetData("charge_flag_dict", "sys_yes_no", "bill_item_class_dict")
);

const queryParams = ref<OutpFeesMaster>({
  pageNum: 1,
  pageSize: 10,
  name: "",
  orgId: userInfo.orgId,
  outpFeesMasterId: '',
  operationUserName: userInfo.nickName
});
const dateRange = ref([date + "00:00:00", date + "23:59:59"]);


/** 查询表集合 */
function getList() {
  selectPageOutpFeesMaster(proxy.$addDateRange(queryParams.value, dateRange.value)).then(
    (response: any) => {
      outpFeesMasterList.value = response.rows;
      if (outpFeesMasterList.value) {
        outpFeesMasterList.value.forEach((masterItem: any) => {
          masterItem.paymentsMoneyVoList.forEach((item: any) => {
            item.charges = Number(item.charges) - Number(item.refundAmount)
          })
        })

      }
      total.value = response.total;
    }
  );
}

function handleQuery() {
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParamsRef.value.resetFields();
  // proxy.resetForm("queryRef");
  handleQuery();
}

/**
 * 小票打印
 * @param row
 */
function prescPrint(row: any) {
  let url = "/business/outpFeesMaster/receiptPrint";
  const formData = new FormData()
  formData.append("feesNo", row.feesNo)
  formData.append("orgId", userInfo.orgId)
  // pdf打印 、打印预览
  proxy.$printPdfPublic(url, formData).then(res => {
    if (res) {
      objectUrl.value = URL.createObjectURL(res)
    } else {
      console.error('打印失败')
    }
  })
}


/** 打印收费记录 */
function printMasterFun(row) {
  invoiceEBillOutpatientFun(row)
}

/**
 * 打印收费票据
 */
function printInvoiceIssueFun(row) {
  getInvoiceIssuePdfUrl(row.feesNo, row.orgId).then((res: any) => {
    console.log(res)
    if (res.data) {
      window.open(res.data.pictureUrl, "_blank");
    }
  })
}


/**
 * 医疗门诊电子票据开具接口
 */
function invoiceEBillOutpatientFun(row) {
  const data = {
    // 正常收款
    isRedFlush: "1",
    orgId: userInfo.orgId,
    feesNo: row.feesNo,
    // 门诊电子票据开具
    oupOrInp: "1",
  }
  invoiceEBillOutpatient(data).then((res: resType) => {
    if (res.data.code === "200") {
      ElMessage.success(res.data.msg)
    } else {
      ElMessage.error(res.data.msg)
    }
  })
}

/**
 * 门诊电子票据冲红
 * @param row
 */
function writeOffEBillFun(row) {
  const data = {
    // 冲红
    isRedFlush: "2",
    orgId: userInfo.orgId,
    feesNo: row.feesNo,
    // 门诊电子票据冲红
    oupOrInp: "1",
    placeCode: '001',
    reason: "开错重开",
    operator: userInfo.nickName
  }
  writeOffEBill(data).then((res: resType) => {
    if (res.data.code === "200") {
      ElMessage.success(res.data.msg)
    } else {
      ElMessage.error(res.data.msg)
    }
  })
}

/** 打印收费明细 */
function printDetailFun() {
}

/**作废 */
function abolishFun(row: any) {
  ElMessageBox.confirm("确定要作废吗？", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    abolishOutpFeesMaster(row.feesNo, queryParams.value.orgId).then((res: any) => {
      ElMessage.success("作废操作成功")
      handleQuery();
    })
  });
}

/** 收费主记录行击事件加载收费明细 */
function rowClick(row: OutpFeesMaster) {
  listOutpFeesDetail({outpFeesMasterId: row.outpFeesMasterId}).then((res: resType) => {
    outpFeesDetailList.value = res.data;
  });
}

/* 表格合并列和行 */
function objectSpanMethod({row, column, rowIndex, columnIndex}) {
  // 定位到需要合并的那一列 下标
  if (columnIndex === 0 || columnIndex === 1) {
    const _row = flitterData(outpFeesDetailList.value, columnIndex).one[rowIndex];
    const _col = _row > 0 ? 1 : 0;
    return {
      rowspan: _row,
      colspan: _col,
    };
  }
}

/**合并表格的第一列，处理表格数据 */
function flitterData(arr, columnIndex) {
  let spanOneArr: any = [];
  let concatOne = 0;
  arr.forEach((item, index) => {
    if (index === 0) {
      spanOneArr.push(1);
    } else {
      //注意这里的packItemName是表格绑定的字段，根据自己的需求来改
      if (columnIndex === 0) {
        if (item.applyNo === arr[index - 1].applyNo) {
          //第一列需合并相同内容的判断条件
          spanOneArr[concatOne] += 1;
          spanOneArr.push(0);
        } else {
          spanOneArr.push(1);
          concatOne = index;
        }
      } else if (columnIndex === 1) {
        if (
          item.packItemName === arr[index - 1].packItemName &&
          item.applyNo === arr[index - 1].applyNo
        ) {
          //第二列需合并相同内容的判断条件
          spanOneArr[concatOne] += 1;
          spanOneArr.push(0);
        } else {
          spanOneArr.push(1);
          concatOne = index;
        }
      }
    }
  });
  return {
    one: spanOneArr,
  };
}

// 便捷门诊-》全部查询表单清空
function convenientToResetQuery() {
  queryParamsRef.value.resetFields();
  queryParams.value.outpFeesMasterId = ''
}

/**
 * 便捷门诊打开初始化函数
 * @param outpFeesMasterId
 */
function initQuery(outpFeesMasterId) {
  queryParams.value.outpFeesMasterId = outpFeesMasterId
  handleQuery()
}

// handleQuery()

defineExpose({
  initQuery,
  convenientToResetQuery,
  handleQuery
})
</script>

<style scoped></style>
